package com.example.exceldemo.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.enums.CellExtraTypeEnum;
import com.example.exceldemo.entity.BaseData;
import com.example.exceldemo.listener.DynamicEasyExcelListener;
import com.example.exceldemo.listener.DynamicEasyExcelListener1;
import com.example.exceldemo.resp.CrossResp;
import com.example.exceldemo.service.CrossImpExcelService;
import com.example.exceldemo.service.ImportExcelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @Description
 * @Author xiaohuang
 * @Date 2025/2/18
 */
@Api(tags = "excel导入")
@RestController("imp")
public class ImpExcelController {
    @Autowired
    private ImportExcelService easyExcelService;
    @Autowired
    private CrossImpExcelService crossImpExcelService;

    /**
     * easyExcel简单导入
     */
    @PostMapping("easy/simple")
    @ApiOperation(value = "easyExcel简单导入")
    public void impEasyExcel(@RequestParam(required = true) @RequestBody MultipartFile file) {
        easyExcelService.importExcel(file);
    }

    /**
     * easyExcel多sheet导入
     */
    @PostMapping("easy/manySheet")
    @ApiOperation(value = "easyExcel多sheet导入（实体类不同）")
    public void manyEasySheet(@RequestParam(required = true) @RequestBody MultipartFile file) {
        easyExcelService.manyEasySheet(file);
    }

    /**
     * easypoi简单导入
     */
    @PostMapping("easypoi/simple")
    @ApiOperation(value = "easyPoi简单导入")
    public void impEasyPoiExcel(@RequestParam(required = true) @RequestBody MultipartFile file) {
        easyExcelService.impEasyPoiExcel(file);
    }

    /**
     * easypoi简单导入
     */
    @PostMapping("easypoi/sheet")
    @ApiOperation(value = "easyPoi多sheet导入(实体类不同)")
    public void impEasyPoiSheet(@RequestParam(required = true) @RequestBody MultipartFile file) {
        easyExcelService.impEasyPoiSheet(file);
    }
    /**
     * easypoi简单导入
     */
    @PostMapping("easypoi/sheet/alike")
    @ApiOperation(value = "easyPoi多sheet导入(实体类相同)")
    public void impEasyPoiAlikeSheet(@RequestParam(required = true) @RequestBody MultipartFile file) {
        easyExcelService.impEasyPoiAlikeSheet(file);
    }


    @PostMapping("poi/merge")
    @ApiOperation(value = "poi解析合并单元格（遍历解析）")
    public List<String[]> poiMergeExcel(@RequestParam(required = true) @RequestBody MultipartFile file) {
        List<String[]> list = crossImpExcelService.poiMergeExcel(file);
        return list;
    }


    @ApiOperation("easyexcel解析合并单元格(注解+监听器)")
    @PostMapping("easy/listener/merge")
    public List<CrossResp> importPermissionTableV1(@RequestParam("file") MultipartFile file) throws Exception {
        List<CrossResp> permissionList = new ArrayList<>();
        try {
            //1：是正文起始行，用于处理合并单元格
            DynamicEasyExcelListener<CrossResp> listener = new DynamicEasyExcelListener(null, 1);
            EasyExcel.read(file.getInputStream(), CrossResp.class, listener).extraRead(CellExtraTypeEnum.MERGE).sheet().doRead();
            permissionList = listener.getList();
        } catch (IOException e) {
            e.printStackTrace();
            throw new IllegalArgumentException(e.getMessage());
        }
        return permissionList;
    }

    /**
     * 读取单元格带图片
     */
    @ApiOperation("poi解析带图片的单元格（支持xls,xlsx）")
    @PostMapping("poi/img")
    public void poiReadImg(@NotNull(message = "sheet序号不能为空") @RequestParam("sheetNo") Integer sheetNo,
                           @NotNull(message = "未选择上传的文件") @RequestParam("file") MultipartFile file) {
        crossImpExcelService.poiReadImg(file, sheetNo);
    }

    @ApiOperation("easy解析横向+纵向合并单元格(注解+监听器)")
    @PostMapping("easy/listener/crossMerge")
    public List<BaseData> crossMerge(HttpServletRequest request, @NotNull(message = "未选择上传的文件") @RequestParam("file") MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            // 初始化监听器
            DynamicEasyExcelListener1 listener1 = new DynamicEasyExcelListener1(request, 1);
            // 读取全部 sheet 并处理合并单元格
            EasyExcel.read(inputStream, BaseData.class, listener1)
                    .headRowNumber(1)
                    .extraRead(CellExtraTypeEnum.MERGE)
                    .sheet(1)
                    .doRead();
            return listener1.getList();
        } catch (IOException e) {
            throw new RuntimeException("文件读取失败", e);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("非法参数或文件", e);
        } catch (Exception e) {
            throw new RuntimeException("未知错误", e);
        }
    }


}
